package com.inspinia.upms.client.filter;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.Token;
import com.baomidou.kisso.common.shiro.SSOAuthToken;
import com.inspinia.base.common.model.BaseConstants;
import com.inspinia.base.common.model.UserCacheKeys;
import com.inspinia.config.common.config.RedisConfig;
import com.inspinia.upms.common.model.user.UpmsUser;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.crazycake.shiro.RedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * @author 客户端局部会话认证与拦截
 */
public class ClientAuthFilter extends AccessControlFilter {

    protected Logger logger = LoggerFactory.getLogger(ClientAuthFilter.class);

    /**
     * 踢出后到的地址
     */
    private String kickoutUrl;
    /**
     * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
     */
    private boolean kickoutAfter = false;
    private int maxSession = 1;
    public static int MAX_SESSION = 1;

    private SessionManager sessionManager;
    private SessionDAO sessionDAO;
    private RedisManager redisManager;


    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        //cookie默认认证
        Token token = SSOHelper.getToken((HttpServletRequest) request);

        if (token == null) {
            WebUtils.issueRedirect(request, response,super.getLoginUrl());
            return false;
        }
        //处理登录
        return loginToken(request,response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request,response);
        if (!subject.isAuthenticated() && subject.isRemembered()){
            return true;
        }
        return true;
    }

    /**
     * shiro会话登录认证
     * @param request
     * @param response
     */
    private boolean loginToken(ServletRequest request, ServletResponse response) throws IOException {
        //cookie默认认证
        Token token = SSOHelper.getToken((HttpServletRequest) request);

        Subject subject = getSubject(request,response);

        Session session = subject.getSession();

        if (session != null) {
            session.touch();
        }
        if (!subject.isAuthenticated()) {
            subject.login(new SSOAuthToken(token));
            logger.info("client auth success. ");
        }
        return isKickout(subject,request,response);
    }

    /**
     * 验证session重复，踢出操作
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    private boolean isKickout(Subject subject, ServletRequest request, ServletResponse response) throws IOException {
        Session session = subject.getSession();
        UpmsUser user = (UpmsUser) subject.getPrincipal();
        Serializable sessionId = session.getId();
        String username = user.getUserName();
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String requestSource = String.valueOf(httpServletRequest.getHeader(BaseConstants.REQUEST_SOURCE_HEADER));
        byte[] cacheKey;
        //根据不同的请求处理来源进行用户管理
        if (BaseConstants.REQUEST_APP_SOURCE.equals(requestSource)) {
            cacheKey = UserCacheKeys.getUsernameSessionKey(username + "_app_" + user.getUserId()).getBytes();
        } else {
            cacheKey = UserCacheKeys.getUsernameSessionKey(username).getBytes();
        }
        byte[] bytes = redisManager.get(cacheKey);
        //用户在系统中的sessionId集合
        ArrayList<Serializable> deque;
        if (bytes != null) {
            deque = SerializationUtils.deserialize(bytes);
        } else {
            deque = new ArrayList<>();
        }

        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            deque.add(sessionId);
            redisManager.set(cacheKey, SerializationUtils.serialize(deque), RedisConfig.timeout);
        }

        //如果队列里的sessionId数超出最大会话数，开始踢人
        int originSize = deque.size();
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            //如果踢出后者
            if (!kickoutAfter) {
                kickoutSessionId = deque.get(deque.size() - 1);
                deque.remove(deque.size() - 1);
            } else {
                //否则踢出前者
                kickoutSessionId = deque.get(0);
                deque.remove(0);
            }
            try {
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if (kickoutSession != null) {
                    //设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute("kickout", true);
                }
            } catch (Exception e) {//ignore exception
            }
        }

        //如果执行了踢出操作，那么这个时候的缓存应当被更新。
        if (originSize != deque.size()) {
            redisManager.set(cacheKey, SerializationUtils.serialize(deque), RedisConfig.timeout);
        }

        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute("kickout") != null) {
            //会话被踢出了
            try {
                subject.logout();
            } catch (Exception e) { //ignore
            }
            saveRequest(request);
            WebUtils.issueRedirect(request, response, kickoutUrl);
            return false;
        }
        return true;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public RedisManager getRedisManager() {
        return redisManager;
    }

    public void setRedisManager(RedisManager redisManager) {
        this.redisManager = redisManager;
    }

    public SessionDAO getSessionDAO() {
        return sessionDAO;
    }

    public void setSessionDAO(SessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
        //由于无法注入该类，导致在websocketController中获取到该值。因此采用static的方式。由于spring的单例，这样做一般不会出问题。
        MAX_SESSION = maxSession;
    }

    public int getMaxSession() {
        return maxSession;
    }
}